using ERP_SaaS_WinForm.生产计划_派单_车间.ProductPlan;
using ERP_SaaS_WinForm.生产计划_派单_车间;
using ERP_SaaS_WinForm.销售.Sales;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SaleApiResponse = ERP_SaaS_WinForm.销售.Sales.SaleApiResponse;
using ERP_SaaS_WinForm.登录.Model;
using System.Net.Sockets;

namespace ERP_SaaS_WinForm.销售
{
    /// <summary>
    /// 销售管理主窗体
    /// 包含客户管理、客户单价管理、折扣方案管理、销售合同管理等功能
    /// </summary>
    public partial class Sale : Form
    {
        /// <summary>
        /// 构造函数 - 初始化销售管理窗体
        /// </summary>
        public Sale()
        {
            InitializeComponent();
        }

        #region 客户管理功能

        /// <summary>
        /// 客户查询按钮点击事件
        /// 根据客户名称查询客户信息并显示在DataGridView中
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private async void dtnCha_Click(object sender, EventArgs e)
        {
            // API基础地址
            string baseUrl = "http://10.223.8.6:3530/api/Client/GetClient";

            // 获取查询的客户名称并去除空格
            string clientName = txtClientName.Text.Trim();

            // 创建查询的参数列表
            var queryParams = new List<string>();
            if (!string.IsNullOrEmpty(clientName))
            {
                queryParams.Add($"clientName={clientName}");
            }

            // 拼接完整的URL
            string fullUrl = $"{baseUrl}?{string.Join("&", queryParams)}";

            // 使用HttpClient发送请求
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    // 异步发送Get请求
                    HttpResponseMessage response = await client.GetAsync(fullUrl);
                    // 确保响应成功（否则抛出异常）
                    response.EnsureSuccessStatusCode();
                    // 读取响应内容为字符串
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    // 反序列化 JSON 响应到 SaleApiResponse 对象
                    SaleApiResponse apiResponse = JsonConvert.DeserializeObject<SaleApiResponse>(jsonResponse);

                    // 检查 API 响应码
                    if (apiResponse.code == 200)
                    {
                        // 将数据绑定到 DataGridView
                        dgvClinent.DataSource = apiResponse.data;
                        // 如果存在 clientName 列，隐藏它
                        if (dgvClinent.Columns.Contains("clientName"))
                        {
                            dgvClinent.Columns["clientName"].Visible = false;
                        }
                    }
                    else
                    {
                        // 显示错误信息
                        MessageBox.Show($"查询失败: {apiResponse.msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"查询客户数据时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        #endregion

        #region 窗体初始化和数据加载

        /// <summary>
        /// 窗体加载事件 - 初始化所有数据和事件绑定
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private async void Sale_Load(object sender, EventArgs e)
        {
            // 调用查询方法初始化数据
            dtnCha_Click(sender, e); // 客户显示
            dtnClientPrice_Click(sender, e); // 客户单价显示

            // 初始化新增页编号
            if (txtClientPriceCode != null)
            {
                txtClientPriceCode.Text = GenerateClientPriceCode();
            }

            // 初始化客户ID存储
            if (txtClient.Tag == null)
            {
                txtClient.Tag = "";
            }

            // 添加DataGridView的事件处理
            dgvClientPrice.CellClick += DgvClientPrice_CellClick;
            dgvClinent.CellFormatting += DgvClinent_CellFormatting;
            dgvContract.CellFormatting += DgvContract_CellFormatting;//状态
            dgvContract.CellClick += DgvContract_CellClick;//删除按钮点击事件

            // 加载折扣方案数据
            await LoadDiscountData();

            // 加载销售合同数据
            await LoadContractData();
        }

        /// <summary>
        /// 加载折扣方案数据
        /// </summary>
        private async Task LoadDiscountData()
        {
            try
            {

                string DiscountUrl = "http://10.223.8.6:3530/api/Discount/GetDiscount";
                using (HttpClient Dclient = new HttpClient())
                {
                    //异步发送get的请求
                    HttpResponseMessage responseMessage = await Dclient.GetAsync(DiscountUrl);

                    responseMessage.EnsureSuccessStatusCode();
                    string DjsonResponse = await responseMessage.Content.ReadAsStringAsync();

                    DiscountApiResponse discount = JsonConvert.DeserializeObject<DiscountApiResponse>(DjsonResponse);
                    if (discount.code == 200)
                    {
                        dgvDiscount.DataSource = discount.data;
                    }
                    else
                    {
                        // 显示错误信息
                        MessageBox.Show($"查询折扣方案失败: {discount.msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载折扣方案数据时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 加载销售合同数据
        /// </summary>
        private async Task LoadContractData()
        {
            try
            {
                string CUrl = "http://10.223.8.6:3530/api/Contract/ShowContract";
                using (HttpClient Cclient = new HttpClient())
                {
                    HttpResponseMessage responseMessage = await Cclient.GetAsync(CUrl);
                    responseMessage.EnsureSuccessStatusCode();
                    string CjsonResponse = await responseMessage.Content.ReadAsStringAsync();

                    ContractApiResponse discount = JsonConvert.DeserializeObject<ContractApiResponse>(CjsonResponse);
                    if (discount.code == 200)
                    {
                        dgvContract.DataSource = discount.data;
                    }
                    else
                    {
                        // 显示错误信息
                        MessageBox.Show($"查询销售合同失败: {discount.msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载销售合同数据时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region 客户单价管理功能

        /// <summary>
        /// 客户单价查询按钮点击事件
        /// 根据客户名称查询客户单价信息
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private async void dtnClientPrice_Click(object sender, EventArgs e)
        {
            string clientPrice = "http://10.223.8.6:3530/api/ClientPrice/GetClientPrice";
            string clientNames = txtClienNames.Text.Trim(); // 查询客户名称，去除空格

            // 创建查询的参数列表
            var queryParam = new List<string>();
            if (!string.IsNullOrEmpty(clientNames))
            {
                queryParam.Add($"clientNames={clientNames}");
            }

            // 拼接完整的URL
            string clientPricefullUrl = $"{clientPrice}?{string.Join("&", queryParam)}";

            using (HttpClient client = new HttpClient())
            {
                try
                {
                    HttpResponseMessage responses = await client.GetAsync(clientPricefullUrl);
                    responses.EnsureSuccessStatusCode();
                    string jsonResponses = await responses.Content.ReadAsStringAsync();
                    ClientPriceApiResponse apiResponses = JsonConvert.DeserializeObject<ClientPriceApiResponse>(jsonResponses);

                    if (apiResponses.code == 200)
                    {
                        dgvClientPrice.DataSource = apiResponses.data;
                        if (dgvClientPrice.Columns.Contains("clientNames"))
                        {
                            dgvClientPrice.Columns["clientNames"].Visible = false;
                        }
                    }
                    else
                    {
                        // 显示错误信息  
                        MessageBox.Show($"查询客户单价失败: {apiResponses.msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"查询客户单价时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        #endregion

        #region 计算功能

        /// <summary>
        /// 自动计算总金额
        /// 根据产品单价和数量自动计算总金额
        /// </summary>
        private void CalculateTotalAmount()
        {
            try
            {
                decimal price = 0;
                decimal quantity = 0;
                decimal totalAmount = 0;

                // 尝试将产品单价和数量转换为小数
                if (!string.IsNullOrEmpty(txtProductPrice.Text) && decimal.TryParse(txtProductPrice.Text, out price) &&
                    !string.IsNullOrEmpty(txtProductQuantity.Text) && decimal.TryParse(txtProductQuantity.Text, out quantity))
                {
                    totalAmount = price * quantity;
                    txtTotalAmount.Text = totalAmount.ToString("F2");
                }
                else
                {
                    txtTotalAmount.Text = "0.00";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("计算总金额时出错: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 产品单价文本变化事件
        /// 当单价发生变化时自动重新计算总金额
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void txtProductPrice_TextChanged(object sender, EventArgs e)
        {
            CalculateTotalAmount();
        }

        /// <summary>
        /// 产品数量文本变化事件
        /// 当数量发生变化时自动重新计算总金额
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void txtProductQuantity_TextChanged(object sender, EventArgs e)
        {
            CalculateTotalAmount();
        }

        #endregion

        #region 选择功能

        /// <summary>
        /// 选择客户按钮点击事件
        /// 打开客户选择窗体并获取选中的客户信息
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void btnSelectClient_Click(object sender, EventArgs e)
        {
            Client client = new Client();
            if (client.ShowDialog() == DialogResult.OK && client.SelectedClient != null)
            {
                var c = client.SelectedClient;
                txtClient.Text = client.SelectedClient.ClientName;
                // 存储客户ID到Tag属性中（使用ClientId作为数据库主键）
                txtClient.Tag = c.ClientId;
            }
        }

        /// <summary>
        /// 选择产品按钮点击事件
        /// 打开产品选择窗体并获取选中的产品信息
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void btnSelectProduct_Click(object sender, EventArgs e)
        {
            var selectProduct = new SelectProduct();
            if (selectProduct.ShowDialog() == DialogResult.OK && selectProduct.SelectedProduct != null)
            {
                var p = selectProduct.SelectedProduct;
                txtProduct.Text = p.ProductName;
                txtProductCode.Text = p.ProductCode;
                txtProductSpec.Text = p.Specification;
            }
        }

        #endregion

        #region 客户单价添加功能

        /// <summary>
        /// 添加客户单价按钮点击事件
        /// 验证输入数据并调用API添加客户单价记录
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private async void btnAddClientPrice_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证输入数据
                if (!ValidateClientPriceInput())
                {
                    return;
                }

                // 创建客户单价数据对象
                var clientPriceData = CreateClientPriceData();

                // 调用API添加客户单价
                await AddClientPriceToApi(clientPriceData);

            }
            catch (Exception ex)
            {
                MessageBox.Show("添加客户单价时出错: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 验证客户单价输入数据
        /// </summary>
        /// <returns>验证是否通过</returns>
        private bool ValidateClientPriceInput()
        {
            // 验证客户名称
            if (string.IsNullOrEmpty(txtClient.Text))
            {
                MessageBox.Show("请输入客户名称", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            // 验证客户ID是否存在
            if (txtClient.Tag == null || txtClient.Tag.ToString() == "0")
            {
                MessageBox.Show("请先选择有效的客户", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            // 验证产品名称
            if (string.IsNullOrEmpty(txtProduct.Text))
            {
                MessageBox.Show("请输入产品名称", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            // 验证产品单价
            if (string.IsNullOrEmpty(txtProductPrice.Text))
            {
                MessageBox.Show("请输入产品单价", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            // 验证产品数量
            if (string.IsNullOrEmpty(txtProductQuantity.Text))
            {
                MessageBox.Show("请输入产品数量", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 创建客户单价数据对象
        /// </summary>
        /// <returns>客户单价数据对象</returns>
        private object CreateClientPriceData()
        {
            // 将输入转换为后端期望的类型（Price/TotalAmount: double，Numder: int）
            if (!double.TryParse(txtProductPrice.Text.Trim(), out double priceValue))
            {
                throw new ArgumentException("单价格式不正确");
            }
            if (!int.TryParse(txtProductQuantity.Text.Trim(), out int quantityValue))
            {
                throw new ArgumentException("数量必须为整数");
            }
            if (!double.TryParse(txtTotalAmount.Text.Trim(), out double totalAmountValue))
            {
                throw new ArgumentException("总金额格式不正确");
            }

            // 创建客户单价对象（与 AddClientPriceCommand 属性对齐）
            return new
            {
                ClientPriceCode = txtClientPriceCode.Text.Trim(),
                ClientId = int.Parse(txtClient.Tag?.ToString() ?? "0"), // 转换为int类型
                ProductCode = txtProductCode.Text.Trim(),
                Price = priceValue,
                Numder = quantityValue,
                TotalAmount = totalAmountValue,
                ClientPriceRemark = txtRemark.Text.Trim()
            };
        }

        /// <summary>
        /// 调用API添加客户单价
        /// </summary>
        /// <param name="clientPriceData">客户单价数据</param>
        private async Task AddClientPriceToApi(object clientPriceData)
        {
            // 转换为JSON
            string jsonData = JsonConvert.SerializeObject(clientPriceData);

            // 调用API添加客户单价
            string apiUrl = "http://10.223.8.6:3530/api/ClientPrice/AddClientPrice";
            using (HttpClient client = new HttpClient())
            {
                var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await client.PostAsync(apiUrl, content);
                string jsonResponse = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    dynamic result = JsonConvert.DeserializeObject(jsonResponse);
                    if (result != null && result.code == 200)
                    {
                        MessageBox.Show("添加成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        // 检查是否需要设置折扣方案
                        await CheckAndSetupDiscount(clientPriceData);

                        // 清空输入框并刷新列表
                        ClearClientPriceInputs();
                        tabControl1.SelectedTab = tabPage2;
                        dtnClientPrice_Click(this, EventArgs.Empty);
                        tabControl1.SelectedTab = tabPage3;
                        txtClientPriceCode.Text = GenerateClientPriceCode();
                    }
                    else
                    {
                        MessageBox.Show("添加失败: " + (result?.msg ?? jsonResponse), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    // 显示后端返回的错误详情，便于定位
                    MessageBox.Show($"添加失败：{response.StatusCode}\n{jsonResponse}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// 检查并设置折扣方案
        /// </summary>
        /// <param name="clientPriceData">客户单价数据</param>
        private async Task CheckAndSetupDiscount(object clientPriceData)
        {
            // 获取总金额
            var totalAmountProperty = clientPriceData.GetType().GetProperty("TotalAmount");
            if (totalAmountProperty != null && totalAmountProperty.GetValue(clientPriceData) is double totalAmountValue)
            {
                // 检查总金额是否满1000，如果满足条件则跳转到折扣方案页面
                if (totalAmountValue >= 1000)
                {
                    var confirmDiscount = MessageBox.Show(
                        $"总金额 {totalAmountValue:F2} 元已达到折扣方案条件（满1000元），是否要设置折扣方案？",
                        "折扣方案提示",
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question);

                    if (confirmDiscount == DialogResult.Yes)
                    {
                        await SetupDiscount();
                    }
                }
            }
        }

        /// <summary>
        /// 设置折扣方案
        /// </summary>
        private async Task SetupDiscount()
        {
            // 创建折扣方案窗体并传递产品信息
            AddDiscount addDiscount = new AddDiscount
            {
                ClientPriceCode = txtClientPriceCode.Text.Trim(),
                ProductCode = txtProductCode.Text.Trim(),
                ProductName = txtProduct.Text.Trim(),
                Specification = txtProductSpec.Text.Trim(),
                TotalAmount = double.Parse(txtTotalAmount.Text.Trim()).ToString("F2"),
                DiscountName = txtClient.Text.Trim() + "折扣方案"
            };

            // 显示折扣方案窗体
            var discountDialogResult = addDiscount.ShowDialog(this);

            // 检查是否需要刷新折扣方案列表并跳转
            if (discountDialogResult == DialogResult.OK && addDiscount.Tag?.ToString() == "RefreshDiscountList")
            {
                // 跳转到折扣方案显示页面
                tabControl1.SelectedTab = tabPage4; // 假设折扣方案显示在第四个标签页

                // 刷新折扣方案列表
                RefreshDiscountList();
            }
        }

        #endregion

        #region 工具方法

        /// <summary>
        /// 清空客户单价输入框
        /// 重置所有输入控件到初始状态
        /// </summary>
        private void ClearClientPriceInputs()
        {
            if (txtClientPriceCode != null)
            {
                txtClientPriceCode.Text = GenerateClientPriceCode();
            }
            txtClient.Text = "";
            txtClient.Tag = null; // 清空客户ID
            txtProduct.Text = "";
            txtProductCode.Text = "";
            txtProductSpec.Text = "";
            txtProductPrice.Text = "";
            txtProductQuantity.Text = "";
            txtTotalAmount.Text = "0.00";
            txtRemark.Text = "";
        }

        /// <summary>
        /// 编号自动生成
        /// 根据现有编号自动生成新的客户单价编号
        /// </summary>
        /// <returns>生成的编号</returns>
        private string GenerateClientPriceCode()
        {
            try
            {
                string prefix = "KHDJ";
                int maxNum = 0;
                if (dgvClientPrice != null && dgvClientPrice.Rows.Count > 0)
                {
                    foreach (DataGridViewRow row in dgvClientPrice.Rows)
                    {
                        if (row.IsNewRow) continue;
                        var value = row.Cells["Column8"] != null ? row.Cells["Column8"].Value?.ToString() : null;
                        if (string.IsNullOrWhiteSpace(value)) continue;
                        if (!value.StartsWith(prefix)) continue;
                        var numPart = value.Substring(prefix.Length);
                        if (int.TryParse(numPart, out int n))
                        {
                            if (n > maxNum) maxNum = n;
                        }
                    }
                }
                return $"{prefix}{(maxNum + 1).ToString("D3")}";
            }
            catch
            {
                return "KHDJ001";
            }
        }

        #endregion

        #region 事件处理

        /// <summary>
        /// TabControl选中索引变化事件
        /// 当切换到客户单价新增标签页时自动生成新编号
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedTab == tabPage3)
            {
                txtClientPriceCode.Text = GenerateClientPriceCode();
            }
        }

        #endregion

        #region DataGridView事件处理

        /// <summary>
        /// 客户单价DataGridView单元格点击事件
        /// 处理修改、删除、折扣方案等操作
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private async void DgvClientPrice_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;

            // 处理修改按钮点击
            if (e.ColumnIndex == dgvClientPrice.Columns["ColumnEditClientPrice"].Index)
            {
                await HandleEditClientPrice(e.RowIndex);
            }
            // 处理删除按钮点击
            else if (e.ColumnIndex == dgvClientPrice.Columns["ColumnDeleteClientPrice"].Index)
            {
                await HandleDeleteClientPrice(e.RowIndex);
            }
            // 处理折扣方案按钮点击
            else if (e.ColumnIndex == dgvClientPrice.Columns["ColumnDisCount"].Index)
            {
                await HandleDiscountSetup(e.RowIndex);
            }
        }

        /// <summary>
        /// 处理修改客户单价
        /// </summary>
        /// <param name="rowIndex">行索引</param>
        private async Task HandleEditClientPrice(int rowIndex)
        {
            // 获取当前行的客户单价数据
            var row = dgvClientPrice.Rows[rowIndex];
            var clientPriceIdObj = row.Cells["Column16"].Value; // Id 列
            int clientPriceId = 0;
            if (clientPriceIdObj != null) int.TryParse(clientPriceIdObj.ToString(), out clientPriceId);
            var priceCode = row.Cells["Column8"].Value?.ToString();
            var clientName = row.Cells["Column9"].Value?.ToString();
            var productCode = row.Cells["Column10"].Value?.ToString();
            var productName = row.Cells["Column11"].Value?.ToString();
            var spec = row.Cells["Column12"].Value?.ToString();
            var price = row.Cells["Column13"].Value?.ToString();
            var quantity = row.Cells["Column14"].Value?.ToString();
            var totalAmount = row.Cells["Column15"].Value?.ToString();
            var remark = row.Cells["Column17"].Value?.ToString();

            // 创建UpdateClientPrice窗体并传递数据
            UpdateClientPrice updateClientPrice = new UpdateClientPrice(
                clientPriceId,
                priceCode ?? "",
                clientName ?? "",
                productCode ?? "",
                productName ?? "",
                spec ?? "",
                price ?? "",
                quantity ?? "",
                totalAmount ?? "",
                remark ?? "");

            // 模态打开，完成后根据结果刷新列表
            var dialogResult = updateClientPrice.ShowDialog(this);
            if (dialogResult == DialogResult.OK)
            {
                // 重新加载客户单价列表
                dtnClientPrice_Click(this, EventArgs.Empty);
            }
        }

        /// <summary>
        /// 处理删除客户单价
        /// </summary>
        /// <param name="rowIndex">行索引</param>
        private async Task HandleDeleteClientPrice(int rowIndex)
        {
            // 删除当前行
            var row = dgvClientPrice.Rows[rowIndex];
            var idObj = row.Cells["Column16"].Value;
            if (idObj == null || !int.TryParse(idObj.ToString(), out int delId) || delId <= 0)
            {
                MessageBox.Show("未能获取有效的Id，无法删除", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var confirm = MessageBox.Show($"确定要删除编号为 {row.Cells["Column8"].Value?.ToString()} 的客户单价吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confirm != DialogResult.Yes) return;

            try
            {
                string url = $"http://10.223.8.6:3530/api/ClientPrice/DelClientPrice?clientPriceId={delId}";
                using (HttpClient http = new HttpClient())
                {
                    var resp = await http.GetAsync(url);
                    var content = await resp.Content.ReadAsStringAsync();
                    if (resp.IsSuccessStatusCode)
                    {
                        MessageBox.Show("删除成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        dtnClientPrice_Click(this, EventArgs.Empty);
                    }
                    else
                    {
                        MessageBox.Show($"删除失败：{resp.StatusCode}\n{content}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除时出错：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 处理折扣方案设置
        /// </summary>
        /// <param name="rowIndex">行索引</param>
        private async Task HandleDiscountSetup(int rowIndex)
        {
            // 获取当前行的客户单价数据
            var row = dgvClientPrice.Rows[rowIndex];
            var clientPriceIdObj = row.Cells["Column16"].Value; // 客户单价ID
            var priceCode = row.Cells["Column8"].Value?.ToString();
            var clientName = row.Cells["Column9"].Value?.ToString();
            var productCode = row.Cells["Column10"].Value?.ToString();
            var productName = row.Cells["Column11"].Value?.ToString();
            var spec = row.Cells["Column12"].Value?.ToString();
            var totalAmount = row.Cells["Column15"].Value?.ToString();

            // 获取客户单价ID
            int clientPriceId = 0;
            if (clientPriceIdObj != null) int.TryParse(clientPriceIdObj.ToString(), out clientPriceId);

            // 检查总金额是否满1000
            if (double.TryParse(totalAmount, out double amount) && amount >= 1000)
            {
                // 创建折扣方案窗体并传递产品信息
                AddDiscount addDiscount = new AddDiscount
                {
                    ClientPriceId = clientPriceId, // 传递客户单价ID
                    ClientPriceCode = priceCode ?? "",
                    ProductCode = productCode ?? "",
                    ProductName = productName ?? "",
                    Specification = spec ?? "",
                    TotalAmount = totalAmount ?? "0.00",
                    DiscountName = (clientName ?? "") + "折扣方案"
                };

                var dialogResult = addDiscount.ShowDialog(this);

                // 检查是否需要刷新折扣方案列表并跳转
                if (dialogResult == DialogResult.OK && addDiscount.Tag?.ToString() == "RefreshDiscountList")
                {
                    // 跳转到折扣方案显示页面
                    tabControl1.SelectedTab = tabPage4; // 假设折扣方案显示在第四个标签页

                    // 刷新折扣方案列表
                    RefreshDiscountList();
                }
            }
            else
            {
                MessageBox.Show("当前订单金额未达到折扣方案条件（满1000元），无法设置折扣方案。",
                    "折扣方案提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        #endregion

        #region 刷新功能

        /// <summary>
        /// 刷新折扣方案列表
        /// 重新从API获取折扣方案数据并更新显示
        /// </summary>
        private async void RefreshDiscountList()
        {
            try
            {
                // 折扣方案显示
                string DiscountUrl = "http://10.223.8.6:3530/api/Discount/GetDiscount";
                using (HttpClient Dclient = new HttpClient())
                {
                    HttpResponseMessage responseMessage = await Dclient.GetAsync(DiscountUrl);
                    responseMessage.EnsureSuccessStatusCode();
                    string DjsonResponse = await responseMessage.Content.ReadAsStringAsync();

                    DiscountApiResponse discount = JsonConvert.DeserializeObject<DiscountApiResponse>(DjsonResponse);
                    if (discount.code == 200)
                    {
                        dgvDiscount.DataSource = discount.data;

                        // 自动跳转后不需要显示刷新提示，因为用户已经看到了结果
                    }
                    else
                    {
                        // 显示错误信息
                        MessageBox.Show($"刷新折扣方案列表失败：{discount.msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"刷新折扣方案列表时出错：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region 格式化事件处理

        /// <summary>
        /// 客户状态列的格式化事件
        /// 将bool类型的客户状态转换为中文显示
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void DgvClinent_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                var grid = sender as DataGridView;
                var column = grid.Columns[e.ColumnIndex];

                // 处理客户状态列（Column5）
                if (column.DataPropertyName == "ClientState" && e.Value != null)
                {
                    if (bool.TryParse(e.Value.ToString(), out bool stateValue))
                    {
                        // 将bool值转换为中文显示
                        e.Value = stateValue ? "是" : "否";
                        e.FormattingApplied = true;
                    }
                }
            }
        }

        /// <summary>
        /// 销售合同审核状态列的格式化事件
        /// 将int类型的审核状态转换为中文显示
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private async void DgvContract_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                var grid = sender as DataGridView;
                var column = grid.Columns[e.ColumnIndex];

                // 处理销售合同审核状态列（Column32）
                if (column.DataPropertyName == "ContractState" && e.Value != null)
                {
                    if (int.TryParse(e.Value.ToString(), out int stateValue))
                    {
                        // 将int值转换为中文显示：0未审核1已通过2已驳回
                        switch (stateValue)
                        {
                            case 0:
                                e.Value = "未审核";
                                break;
                            case 1:
                                e.Value = "已通过";
                                break;
                            case 2:
                                e.Value = "已驳回";
                                break;
                            default:
                                e.Value = "未知状态";
                                break;
                        }
                        e.FormattingApplied = true;
                    }
                }
            }

            // 注意：删除按钮的点击事件应该在CellClick事件中处理，而不是在CellFormatting中
            // CellFormatting事件只用于格式化显示，不应该处理用户交互
        }

        #endregion

        #region 其他事件

        /// <summary>
        /// TabPage1点击事件（保留方法）
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void tabPage1_Click(object sender, EventArgs e)
        {
            // 预留方法，可根据需要添加功能
        }

        #endregion
        #region 跳转页面
        /// <summary>
        /// 跳转到添加销售合同页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddContracttiaozhuan_Click(object sender, EventArgs e)
        {
            AddContract addContract = new AddContract();
            var result = addContract.ShowDialog(this);
            if (result == DialogResult.OK)
            {
                _ = LoadContractData();
                tabControl1.SelectedTab = tabPage5;
            }
        }
        #endregion

        /// <summary>
        /// 销售合同DataGridView单元格点击事件
        /// 处理删除按钮的点击操作
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private async void DgvContract_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            // 检查是否是删除按钮列被点击，且行索引有效
            if (e.ColumnIndex == dgvContract.Columns["Delete"].Index && e.RowIndex >= 0)
            {
                // 调用删除合同方法
                await DelContract(e.RowIndex);
            }
            // 检查是否是修改按钮列被点击，且行索引有效
            else if (e.RowIndex >= 0)
            {
                // 兼容列名：设计器中列名为 ColumnEnit（修改按钮列）
                var editColumn = dgvContract.Columns["ColumnEnit"];
                if (editColumn != null && e.ColumnIndex == editColumn.Index)
                {
                    // 调用修改合同方法，打开 UpdateContract 窗口并反填数据
                    await EditContracr(e.RowIndex);
                }
            }
        }

        /// <summary>
        /// 删除销售合同
        /// 根据合同ID调用API删除指定的销售合同
        /// </summary>
        /// <param name="rowIndex">要删除的行索引</param>
        private async Task DelContract(int rowIndex)
        {

            // 获取当前行的合同数据
            var contractRow = dgvContract.Rows[rowIndex];
            var idObjs = contractRow.Cells["Column23"].Value; // ContractId列  Column23是id列

            // 验证ID是否有效
            if (idObjs == null || !int.TryParse(idObjs.ToString(), out int contractId) || contractId <= 0)
            {
                MessageBox.Show("未能获取到有效的合同ID，无法删除", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var confrims = MessageBox.Show($"确定要删除编号为{contractRow.Cells["Column24"].Value?.ToString()}的销售合同吗？", "确定删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confrims != DialogResult.Yes) return;
            try
            {
                // 调用删除API
                string deleteUrl = $"http://10.223.8.6:3530/api/Contract/DelContract?ContractId={contractId}";

                using (HttpClient httpClient = new HttpClient())
                {
                   var response=await httpClient.GetAsync(deleteUrl);
                    var contran=await response.Content.ReadAsStringAsync();

                    if (response.IsSuccessStatusCode)
                    {
                        // 删除成功
                        MessageBox.Show("销售合同删除成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        // 重新加载合同数据
                        LoadContractData();
                    }
                    else
                    {
                        // 删除失败，显示错误信息
                        string errorContent = await response.Content.ReadAsStringAsync();
                        MessageBox.Show($"删除销售合同失败：{response.StatusCode}\n{contran}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 修改销售合同
        /// </summary>
        /// <param name="rowIndex"></param>
        /// <returns></returns>
        private async Task EditContracr(int rowIndex)
        {
            var row=dgvContract.Rows[rowIndex];
            var contracrObj = row.Cells["Column23"].Value;//获取Id
            int contracrId = 0;
            if(contracrObj != null) int.TryParse(contracrObj.ToString(),out contracrId);
            var ContractCode = row.Cells["Column24"].Value?.ToString();
            var ContractName = row.Cells["Column25"].Value?.ToString();
            var SigningDate = row.Cells["Column28"].Value?.ToString();
            var ClientIdObj = row.Cells["Column26"].Value; // 客户Id
            int clientId = 0;
            if (ClientIdObj != null) int.TryParse(ClientIdObj.ToString(), out clientId);
            var ClientName = row.Cells["Column27"].Value?.ToString();
            var ShippingDate = row.Cells["Column29"].Value?.ToString();
            var DiscountAmount = row.Cells["Column30"].Value?.ToString();
            var DeliveryAdder = row.Cells["Column31"].Value?.ToString();
            var ContractRemark = row.Cells["Column33"].Value?.ToString();

            UpdateContract updateContract = new UpdateContract(
                contracrId,
                ContractCode ?? "",
                ContractName ?? "",
                SigningDate ?? "",
                clientId,
                ClientName ?? "",
                ShippingDate ?? "",
                DiscountAmount ?? "",
                DeliveryAdder ?? "",
                ContractRemark ?? "" );
            var dialog=updateContract.ShowDialog(this);
            if(dialog==DialogResult.OK)
            {
                LoadContractData();
            }
        }
    }
}